<template>
  <div>
    <el-card shadow="never" v-if="$permiss[1290]" style="margin-bottom: 10px">
      <el-form label-width="100px" ref="form" :model="form" :rules="rulesForm">
        <el-form-item :label="$t('营销APP')" prop="benefitApp">
          <el-select v-model="form.benefitApp" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('注册时间')">
          <el-date-picker
              v-model="form.registerTime"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              :clearable="false"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="searchSms">{{ $t('查询') }}</el-button>
          <el-button @click="resetSearch">{{ $t('重置') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div v-if="$permiss[1291]">
      <SearchForm @search="getSmsRecord" @reset="clearSmsRecord">
        <el-col :span="8" :xs="24" v-if="$permiss[1303]">
          <el-form-item :label="$t('所属租户')">
            <el-select style="width: 100%" v-model="page.adminUserId" clearable>
              <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                         :value="item.adminUserId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('短信渠道')">
            <el-select style="width: 100%" v-model="page.smsName" clearable>
              <el-option v-for="item in smsListChannel" :key="item.smsName" :label="item.smsName"
                         :value="item.smsName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('营销APP')">
            <el-select style="width: 100%" v-model="page.benefitApp" clearable>
              <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                         :value="item.productName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-form-item :label="$t('发送状态')">
            <el-select style="width: 100%" v-model="page.status" clearable>
              <el-option :label="$t('待发送')" :value="0"></el-option>
              <el-option :label="$t('已发送')" :value="1"></el-option>
              <el-option :label="$t('已取消')" :value="2 "></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('操作时间')">
            <el-date-picker
                style="width: 100%"
                value-format="yyyy-MM-dd"
                v-model="page.createTimeValue"
                type="daterange"
                range-separator="~"
                :start-placeholder="$t('开始日期')"
                :end-placeholder="$t('结束日期')">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('发送时间')">
            <el-date-picker
                style="width: 100%"
                value-format="yyyy-MM-dd"
                v-model="page.sendTimeValue"
                type="daterange"
                range-separator="~"
                :start-placeholder="$t('开始日期')"
                :end-placeholder="$t('结束日期')">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </SearchForm>
      <div style="margin: 10px 0;text-align: right">
        <el-button type="primary" @click="batchEdit" v-show="$permiss[1645]">{{ $t('批量编辑') }}</el-button>
        <el-button type="primary" @click="batchCancel" v-show="$permiss[1407]">{{ $t('批量取消') }}</el-button>
        <el-button type="primary" v-show="$permiss[1231]" @click="exportsExcel" :loading="exportsLoading">{{
            $t('导出')
          }}
        </el-button>
      </div>
      <Table :table-column="tableColumn" :table-data="tableData" :page="page"
             :selection="true"
             :loading="loading"
             :select-rows="batchRowsData"
             @handleSelectionChange="(rows)=>batchRowsData = rows"
             @handleSizeChange="(val)=>{page.pageSize = val,getSmsRecord()}"
             @handleCurrentChange="(val)=>{page.pageNum = val,getSmsRecord()}">
        <template slot-scope="{row}" slot="registerStart">
          <span v-if="row.registerStart">{{ row.registerStart }} - {{ row.registerEnd }}</span>
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button v-show="row.status === $t('待发送') && $permiss[1407]" type="text" @click="closeSendSms(row)">
            {{ $t('取消') }}
          </el-button>
          <el-button v-show="row.status === $t('待发送') && $permiss[1645]" type="text" @click="editSms(row)">
            {{ $t('编辑') }}
          </el-button>
        </template>
      </Table>
    </div>
    <Dialog :visible.sync="sendSmsVisible" :title="$t('发送短信')" @confirm="sendSMS" @close="clearSendForm"
            :confirm-loading="confirmLoading"
            @cancel="sendSmsVisible = false">
      <el-form label-width="80px" ref="sendForm" :model="sendForm">
        <el-form-item :label="$t('查询到数据条数')" label-width="120px">
          <div style="line-height: 32px">
            {{ smsTotal }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('短信渠道')" prop="smsName"
                      :rules="[{message: this.$t('请选择'), required: true, trigger: 'blur'}]">
          <el-select v-model="sendForm.smsName" clearable>
            <el-option v-for="item in selectSmsChannel" :key="item.smsName" :label="item.smsName"
                       :value="item.smsName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('短信内容')" prop="msg"
                      :rules="[{message: this.$t('不能为空'), required: true, trigger: 'blur'}]">
          <el-input type="textarea" v-model="sendForm.msg" :rows="6"/>
        </el-form-item>
        <el-form-item :label="$t('发送时间')" prop="sendTimeList"
                      :rules="timeRules"
        >
          <div style="margin-bottom: 10px" v-for="(item,index) in sendForm.sendTimeList">
            <el-date-picker
                type="datetime"
                v-model="sendForm.sendTimeList[index]"
                value-format="yyyy-MM-dd HH:mm"
                popper-class="sendTimeClass"
                :picker-options="{
                disabledDate(time) {
                     return time.getTime() <= (Date.now() - (24 * 60 * 60 * 1000));
                }}"
                :placeholder="$t('选择日期时间')">
            </el-date-picker>
            <span style="margin-left: 5px">
             <el-button icon="el-icon-plus" @click="addContentNum(index)"/>
             <el-button icon="el-icon-minus" type="danger" @click="reduceContentNum(index)"/>
           </span>
          </div>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    编辑短信-->
    <Dialog :visible.sync="editVisible" :title="tableRows.benefitApp + ' - ' + $t('编辑短信')" @confirm="editSmsConfirm"
            @cancel="editVisible = false">
      <el-form label-width="80px" ref="editForm" :model="tableRows">
        <el-form-item :label="$t('短信渠道')">
          <div style="line-height: 32px"> {{ tableRows.smsName }}</div>
        </el-form-item>
        <el-form-item :label="$t('短信内容')" prop="smsMsg" :rules="[
               {message: this.$t('不能为空'), required: true, }
            ]">
          <el-input type="textarea" :rows="4" v-model="tableRows.smsMsg"/>
        </el-form-item>
        <el-form-item :label="$t('发送时间')" prop="sendTime" :rules="[
                  {message: this.$t('请选择'), required: true, trigger:'change'}
             ]">
          <el-date-picker
              style="width:100%"
              :clearable="false"
              value-format="yyyy-MM-dd HH:mm"
              popper-class="sendTimeClass"
              :picker-options="{
                disabledDate(time) {
                     return time.getTime() <= (Date.now() - (24 * 60 * 60 * 1000));
                }}"
              v-model="tableRows.sendTime"
              type="datetime"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </Dialog>

    <!--    批量编辑短信-->
    <BatchEditSms :visible.sync="batchVisible" :data="batchRowsData" :type="4"
                  @batchChange="batchRowsData = [],getSmsRecord()"/>
  </div>
</template>

<script>
import {dateFormatSection, defaultTimeDate} from "@/utils/tools";
import {export_json_to_excel} from "@/utils/exportExcel";
import {selectChannelName} from "@/api/channel";
import {selectProduct, selectTenant} from "@/api/system";
import {selectSmsChannel} from '@/api/system'
import {
  flowTotal,
  flowList,
  flowListExport,
  flowSmsSend,
  flowCloseSmsSend,
  reborrowCloseSmsSend,
  flowBatchEditSms
} from '@/api/marketing'
import BatchEditSms from './batchEditSms'

export default {
  name: "FlowUserSms",
  components: {
    BatchEditSms
  },
  data() {
    return {
      form: {
        benefitApp: null,
        registerTime: defaultTimeDate(7)
      },
      rulesForm: {
        benefitApp: [{message: this.$t('请选择'), required: true, trigger: 'change'}],
      },
      tableColumn: [
        {label: this.$t('营销APP'), prop: 'benefitApp'},
        {label: this.$t('注册时间'), prop: 'registerStart', minWidth: 200, slot: 'registerStart'},
        {label: this.$t('短信渠道'), prop: 'smsName'},
        {label: this.$t('短信内容'), prop: 'smsMsg', minWidth: 250},
        {label: this.$t('发送时间'), prop: 'sendTime', minWidth: 150},
        {label: this.$t('发送状态'), prop: 'status',},
        {label: this.$t('发送条数'), prop: 'sendNum'},
        {label: this.$t('操作人'), prop: 'adminUserName'},
        {label: this.$t('操作时间'), prop: 'createTime', minWidth: 150},
        {label: this.$t('操作'), slot: 'handle', minWidth: 100, fixed: 'right'},
      ],
      tableData: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        createTimeValue: defaultTimeDate(1),
        status: 0
      },
      loading: false,
      marketingChannel: [],
      productList: [],
      selectSmsChannel: [],
      smsListChannel: [],
      sendSmsVisible: false,
      timeRules: [{
        type: 'array', required: true, validator: (rule, value, callback) => {
          if (value.length <= 0 || !value.find(i => i)) {
            return callback(new Error(this.$t('请选择')))
          }
          const filterSendTime = value.filter(item => item)
          for (let i = 0; i < filterSendTime.length; i++) {
            if (new Date(filterSendTime[i]).getTime() < new Date().getTime()) {
              return callback(this.$t('发送时间不能小于当前时间'))
            }
          }
          return callback()
        }, trigger: 'change'
      }],
      sendForm: {
        smsName: null,
        msg: null,
        sendTimeList: ['']
      },
      smsTotal: 0,
      exportsLoading: false,
      tenantList: [],
      confirmLoading: false,
      batchVisible: false,
      batchRowsData: [],
      editVisible: false,
      tableRows: {}
    }
  },
  mounted() {
    this.getSelect()
    this.getSmsRecord()
  },
  methods: {
    // 营销短信查询
    searchSms() {
      this.$refs.form.validate(async v => {
        if (v) {
          const [registerStartTime, registerEndTime] = dateFormatSection(this.form.registerTime || [])
          const params = {
            ...this.form,
            registerStartTime, registerEndTime,
          }
          delete params.registerTime
          const res = await flowTotal(params)
          if (res.code === 1) {
            this.sendSmsVisible = true
            this.smsTotal = res.data || 0
            this.selectSmsChannel = await this.getSmsListChannel({
              productName: this.form.productName
            })
          }
        }
      })
    },
    resetSearch() {
      this.form = {
        timeValue: null,
      }
      this.$refs.form.resetFields()
    },
    // 获取列表
    async getSmsRecord() {
      const [createStartTime, createEndTime] = dateFormatSection(this.page.createTimeValue || [])
      const [sendStartTime, sendEndTime] = dateFormatSection(this.page.sendTimeValue)
      const params = {
        ...this.page,
        sendStartTime, sendEndTime,
        createStartTime, createEndTime,
      }
      delete params.sendTimeValue
      delete params.createTimeValue
      this.loading = true
      const res = await flowList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          const statusObj = {
            0: this.$t('待发送'),
            1: this.$t('已发送'),
            2: this.$t('已取消'),
          }
          item.status = statusObj[item.status]
          return item
        })
        this.page = {
          ...this.page,
          total
        }
        this.loading = false
      } else {
        this.loading = false
      }
    },
    clearSmsRecord() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getSmsRecord()
    },
    clearSendForm() {
      this.$refs.sendForm.resetFields()
    },
    // 短信发送
    sendSMS() {
      this.$refs.sendForm.validate(async v => {
        if (v) {
          if (this.smsTotal <= 0) return this.$message.error(this.$t('当前可发送短信的用户数量为0，无法提交'))
          const [registerStartTime, registerEndTime] = dateFormatSection(this.form.registerTime || [])
          const params = {
            ...this.sendForm,
            ...this.form,
            registerStartTime, registerEndTime,
            sendTimeList: this.sendForm.sendTimeList.filter(item => item)
          }
          this.confirmLoading = true
          delete params.registerTime
          const res = await flowSmsSend(params)
          if (res.code === 1) {
            this.confirmLoading = false
            this.sendSmsVisible = false
            this.$message.success(this.$t('操作成功'))
            this.getSmsRecord()
          } else {
            this.confirmLoading = false
          }
        }
      })
    },
    async getSelect() {
      selectChannelName().then(res => {
        this.marketingChannel = res.data
      })
      selectProduct({status: 1}).then(res => {
        this.productList = res.data
      })
      selectTenant().then(res => {
        this.tenantList = res.data
      })
      this.smsListChannel = await this.getSmsListChannel({type: 3})
    },
    // 获取列表短信渠道
    async getSmsListChannel(params) {
      const res = await selectSmsChannel({...params, type: 3})
      if (res.code === 1) {
        return res.data
      }
    },
    reduceContentNum(index) {
      if (this.sendForm.sendTimeList.length > 1) {
        this.sendForm.sendTimeList.splice(index, 1)
      }
    },
    addContentNum(index) {
      this.sendForm.sendTimeList.push('')
    },
    batchEdit() {
      if (!this.batchValidate()) {
        this.batchVisible = true
      }
    },
    batchValidate() {
      if (this.batchRowsData.length === 0) return this.$message.error(this.$t('请选择短信'))
      const isSend = this.batchRowsData.some(item => item.status !== this.$t('待发送'))
      if (isSend) return this.$message.error(this.$t('状态为待发送的短信才可编辑'))
      return false
    },
    // 批量取消
    async batchCancel() {
      if (!this.batchValidate()) {
        this.$confirm(this.$t('该操作将导致该条短信任务停止执行发送，请确认是否进行该操作') + '?', this.$t('提示'), {
          type: 'warning'
        }).then(async () => {
          const list = this.batchRowsData.map(item => item.id)
          const res = await flowCloseSmsSend(list)
          if (res.code === 1) {
            this.$message.success(this.$t('取消成功'))
            this.getSmsRecord()
          }
        })
      }
    },
    editSms(row) {
      this.tableRows = {...row}
      this.editVisible = true
    },
    // 编辑短信提交
    editSmsConfirm() {
      this.$refs.editForm.validate(async v => {
        if (v) {
          const {id, sendTime, smsMsg: msg, benefitApp} = this.tableRows
          const params = [{id, sendTime, msg, productName:benefitApp}]
          const res = await flowBatchEditSms(params)
          if (res.code === 1) {
            this.$message.success(this.$t('编辑成功'))
            this.editVisible = false
            this.getSmsRecord()
          }
        }
      })
    },
    closeSendSms({id}) {
      this.$confirm(this.$t('该操作将导致该条短信任务停止执行发送，请确认是否进行该操作') + '?', this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const res = await flowCloseSmsSend([id])
        if (res.code === 1) {
          this.$message.success(this.$t('取消成功'))
          this.getSmsRecord()
        }
      })
    },
    //  导出
    async exportsExcel() {
      this.exportsLoading = true;
      const [createStartTime, createEndTime] = dateFormatSection(this.page.createTimeValue || [])
      const [sendStartTime, sendEndTime] = dateFormatSection(this.page.sendTimeValue)
      const params = {
        ...this.page,
        sendStartTime, sendEndTime,
        createStartTime, createEndTime,
      }
      delete params.sendTimeValue
      delete params.createTimeValue
      const res = await flowListExport(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          if (item.registerStart) {
            item.registerStart = item.registerStart + '-' + item.registerEnd
          }
          return item;
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("流量用户短信营销");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    }
  }
}
</script>

<style scoped>

</style>
